package main

import(
    "github.com/codegangsta/martini"
    // _ "github.com/Go-SQL-Driver/MySQL" 
    // "database/sql"
    "encoding/json"
    "io/ioutil"
    "net/http"
    "bytes"
    "html/template"
    "h5utils"
    // "os"
    "fmt"
)

type RequestJson struct {
        Code            int
        Text            string
}

type StudentIdInfo struct {  
    Studentid 	string 	 `json:"studentid"`
} 

type NewStudent struct {  
    SchoolName  string   `json:"schoolName"`
    ClassName   string   `json:"class"`
    Studentid   string   `json:"studentid"`
} 

type WaterInfo struct {  
    Sid         string   `json:"studentid"`
    WaterNumber    int   `json:"waterNumber"`
    // ActionType     int   `json:"actionType"`
} 

type RequestOpenId struct {
    Access_token    string  `json:"access_token"`
    Expires_in      int     `json:"expires_in"`
    Refresh_token   string  `json:"refresh_token"`
    OpenId          string  `json:"openid"`
    Scope           string  `json:"scope"`
}



func main() {
	m := martini.Classic()
    m.Use(martini.Static("static"))
    h5utils.Init()

	m.Get("/", func(w http.ResponseWriter, req *http.Request) string {
		jsonStr := "{\"studentid\":\"oLqIzswoUIxq1xszxpbwjrPP1VX0AA\"}"
        // jsonStr := "{\"schoolName\":\"浙江第一实验小学\", \"class\":\"3年1班\", \"studentid\":\"oLqIzswoUIxq1xszxpbwj\"}"
        // jsonStr := "{\"studentId:oLqIzswoUIxq1xszxpbwjrPP1VX0\", \"actionType\":\"1\"}"
        // jsonStr := "{\"deviceID\":\"450100363\", \"taskId\":\"19\",\"status\":\"Testing\"}"
        body := bytes.NewBuffer([]byte(jsonStr))
        res, err := http.Post("http://maplearch.org/top10Info", "application/json;charset=utf-8", body)
        // res, err := http.Post("http://pj.zlzkj.org:80/wsybc/device/print", "application/json;charset=utf-8", body)
        h5utils.CheckErr(err)
        result, err := ioutil.ReadAll(res.Body)
        res.Body.Close()
        h5utils.CheckErr(err)
        return string(result)
	})

    m.Get("/auth.htm",func(w http.ResponseWriter, req *http.Request) {
        req.ParseForm()
        openId := HttpGet(req.FormValue("code"))
        isExists := h5utils.IfStudentExsist(openId)
        fmt.Println("vopenod: ", openId)
        if (isExists) {
            tp, _ := template.ParseFiles("index.html")
            err := tp.Execute(w, openId)
            h5utils.CheckErr(err)
            
        } else {
            tp, _ := template.ParseFiles("register.html")
            err := tp.Execute(w, openId)
            h5utils.CheckErr(err)
            
        }
    })

	m.Post("/studentInfo",func(req *http.Request) string {
		req.ParseForm()
		body, err := ioutil.ReadAll(req.Body)
        h5utils.CheckErr(err)
		v := StudentIdInfo{}  
    	json.Unmarshal(body, &v)
        return h5utils.SelectStudentInfo(v.Studentid)
	})

    m.Post("/top10Info", func(req *http.Request) string {
        req.ParseForm()
        body, err := ioutil.ReadAll(req.Body)
        h5utils.CheckErr(err)
        v := StudentIdInfo{}  
        json.Unmarshal(body, &v)
        mSid := v.Studentid
        return h5utils.Select10Top(mSid)
        
    })

    m.Post("/newStudent", func(req *http.Request) string{
        req.ParseForm()
        body, err := ioutil.ReadAll(req.Body)
        h5utils.CheckErr(err)
        
        v := NewStudent{}  
        json.Unmarshal(body, &v)
        fmt.Println("json", &v)
    
        if h5utils.IfStudentExsist(v.Studentid) {
            return "{\"data\":\"This student is exists!\"}"
        }

        if h5utils.IfSchoolExsist(v.SchoolName, v.ClassName) {
            return "{\"data\":\"This Tree had been got!\"}"
        } 

        h5utils.InsertTree(v.SchoolName, v.ClassName)
        mTreeInfo := h5utils.SelectData("SELECT * FROM TreeInfo where SchoolName = '" + v.SchoolName + "' and Class = '" + v.ClassName + "'")     
        h5utils.InsertStudent(v.Studentid, mTreeInfo["Tid"])    
            
        return h5utils.SelectStudentInfo(v.Studentid)            
    })

    // m.Post("/updateInfo", func(req *http.Request) string {
        // req.ParseForm()
        // body, err := ioutil.ReadAll(req.Body)
        // if err != nil {
        //     return "{\"data\": \" Request is error !\"}"
        // } else {
        //     v := StudentInfo{}  
        //     json.Unmarshal(body, &v)
        //     fmt.Println("json", &v)
        //     // mSchoolName := v.SchoolName
        //     // mClass := v.Classes
        //     mStudentInfoMap := selectData("SELECT * FROM StudentInfo where Sid = '" + v.Studentid + "'")
        //     if (len(mStudentInfoMap) < 1) {
        //         return "{\"data\": \" This is not exists!\"}"
        //     }

        //     if (v.ActionType == 1) { //water
        //         orderWaterDay := mStudentInfoMap["LastWaterDay"].split("-")
        //         month := time.Now().Month()
        //         day := time.Now().Day()
        //         hasNewDay := false;
        //         var newWaterDay string
        //         if (len(orderWaterDay != 2)) {
        //             hasNewDay = true
        //             newWaterDay = month + "-" + day
        //         } else {
        //             if (orderWaterDay[0] <= month && orderWaterDay[1] <= day) {
        //                 hasNewDay = true
        //                 newWaterDay = month + "-" + day
        //             } else {
        //                 newWaterDay = mStudentInfoMap["LastWaterDay"]
        //             }
        //         }

        //         if (hasNewDay) {
        //             stmt, err = db.Prepare("update StudentInfo set Count=? where uid=?")
        //             checkErr(err)
        //             res, err = stmt.Exec("2", v.Studentid) 
        //             checkErr(err)
        //             affect, err := res.RowsAffected() 
        //             checkErr(err)
        //             fmt.Println(affect)
        //         }
        //     } else if (v.ActionType == 2) { //share

        //     } else {
        //         return "{\"data\": \"Error Type!\"}"
        //     }


        // }
        // return ""
    // })
    m.RunOnAddr(":80")
	m.Run()
}

func HttpGet(code string) string {
    url := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxa2a45eda83686bc4&secret=bd04f14e8e076ab6bb5fa6c88800549b&code="
    url = url + code + "&grant_type=authorization_code"
    resp, err := http.Get(url)
    h5utils.CheckErr(err)
    defer resp.Body.Close()
    body, err := ioutil.ReadAll(resp.Body)
    h5utils.CheckErr(err)
    fmt.Println("body: " , string(body))
    // jsonStr := "{\"access_token\":\"OezXcEiiBSKSxW0eoylIeAZQsK1Si0DySAMa4rL_PS2X8YD3XMSziKCa9oOowuLJdsnvncOMHMJGdoZdCBueMGhxRsEut6R5ZJb"
    // jsonStr = jsonStr + "I2nAKwZLuuhLsZF5NDnwfoHQftRlRdJcgq3N4sBVc6GsuSyRKcg\",\"expires_in\":7200,\"refresh_token\":\"OezXcEiiBSKSxW0eoy"
    // jsonStr = jsonStr + "lIeAZQsK1Si0DySAMa4rL_PS2X8YD3XMSziKCa9oOowuLJWioGCmkMfXLJgn3obs7fNbHjweu77_i5dmeJW2_ZDvIKPrvXwlO8tu36FE49XF24AR"
    // jsonStr = jsonStr + "4zb5uC0zs5q-iUsHcZbA\",\"openid\":\"of4Ilsx5qMXQoCmxE9Lh_eJujPfY\",\"scope\":\"snsapi_userinfo\"}"
    var v RequestOpenId
    json.Unmarshal(body, &v)
    return v.OpenId
}